package com.sea.controller;

import com.sea.pojo.Result;
import com.sea.pojo.User;
import com.sea.utils.JwtUtil;
import com.sea.utils.Md5Util;
import com.sea.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import com.sea.service.UserService;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService us;
    @Autowired
    private StringRedisTemplate srt;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password, @Pattern(regexp = "^\\S{5,16}$") String rePassword) {
        if (!password.equals(rePassword)){
            return Result.error("两次填写的密码不一致");
        }
        User u = us.findByusername(username);
        if (u == null) {
            us.register(username, password);
            return Result.success();
        } else {
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User lu = us.findByusername(username);
        if (lu == null) {
            return Result.error("用户名错误");
        }
        if (Md5Util.getMD5String(password).equals(lu.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", lu.getId());
            claims.put("username", lu.getUsername());
            String token = JwtUtil.genToken(claims);

            ValueOperations<String, String> operations = srt.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);

            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> getUserInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = us.findByusername(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        us.update(user);
        return Result.success();
    }

    @PatchMapping("/updateavatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        us.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatepwd")
    public Result updatepwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        String oldpwd = params.get("old_pwd");
        String newpwd = params.get("new_pwd");
        String repwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldpwd) || !StringUtils.hasLength(newpwd) || !StringUtils.hasLength(repwd)) {
            return Result.error("缺少必要参数");
        }

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User lU = us.findByusername(username);
        if (!lU.getPassword().equals(Md5Util.getMD5String(oldpwd))) {
            return Result.error("原密码填写不正确");
        }

        if (!repwd.equals(newpwd)) {
            return Result.error("两次填写的密码不一致");
        }

        if (newpwd.length() < 5 || newpwd.length() > 16) {
            return Result.error("新密码格式不正确");
        }

        us.updatePwd(newpwd);
        ValueOperations<String, String> operations = srt.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
